<?php

namespace common\models\db;

use Yii;
use common\components\wtools\tools\ArrayHelper;
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use common\components\wsoftdelete\SoftDeleteTrait;
use common\components\wsoftdelete\SoftDeleteBehavior;

/**
 * This is the model class for table "{{%building_order_messages}}".
 *
 * @author
 * @property Adminers $createdByAdmin
 * @property Adminers $updatedByAdmin
 */
class BuildingOrderMessages extends \common\models\db\tables\BuildingOrderMessages
{
    const SCENARIO_TEST = 'test';

    use SoftDeleteTrait;

    public static function getDeletedAtAttribute()
    {
        return "deleted_at";
    }

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors = ArrayHelper::merge($behaviors, [
            'timestamp' => [
                'class' => TimestampBehavior::class,
//                'createdAtAttribute' => false,
//                'updatedAtAttribute' => false,
            ],
            'blameable' => [
                'class' => BlameableBehavior::class,
                'createdByAttribute' => false,
                'updatedByAttribute' => false,
            ],
            'soft-delete' => [
                'class' => SoftDeleteBehavior::class,
                'deletedAtAttribute' => static::getDeletedAtAttribute(),
            ],
        ]);
        return $behaviors;
    }

    public function attributeLabels()
    {
        $attributeLabels = parent::attributeLabels();
        $attributeLabels = ArrayHelper::merge($attributeLabels, [
            'set_bo_status' => "设置施工单状态",
            'message' => "留言",
        ]);
        return $attributeLabels;
    }

    public function rules()
    {
        $rules = parent::rules();
        foreach ($rules as $k => $v) {
            if ($v[1] == 'required'){
                $rules[$k][0] = array_diff($rules[$k][0], ['created_at', 'updated_at']);
            }
        }
        $rules = ArrayHelper::merge($rules, [
//            [[], 'required', 'on' => self::SCENARIO_TEST],
        ]);
        return $rules;
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios = ArrayHelper::merge($scenarios, [
            self::SCENARIO_TEST => [],
        ]);
        return $scenarios;
    }

    public static function getOrSetLastUpdatedAt($updatedAt = 0)
    {
        if ($updatedAt > 0) {
            Yii::$app->cache->delete("db-BuildingOrderMessages-getOrSetLastUpdatedAt");
        }
        return Yii::$app->cache->getOrSet("db-BuildingOrderMessages-getOrSetLastUpdatedAt", function () use ($updatedAt) {
            if ($updatedAt > 0) {
                return $updatedAt;
            }
            $lastModel = static::findWithTrashed()->orderBy(['updated_at' => SORT_DESC])->one();
            return $lastModel ? $lastModel->updated_at : 0;
        });
    }

    /**
     * @return false|mixed|BuildingOrderMessages[]
     */
    public static function getAllWithCache()
    {
        return Yii::$app->cache->getOrSet("db-BuildingOrderMessages-getAllWithCache", function () {
            return static::find()->all();
        }, null);
    }

    /**
     * @param $id
     * @return false|BuildingOrderMessages|mixed
     */
    public static function getByIdWithCache($id)
    {
        return Yii::$app->cache->getOrSet("db-BuildingOrderMessages-getByIdWithCache/{$id}", function () use ($id) {
            return static::findOne($id);
        }, null);
    }

    public function deleteCaches()
    {
        Yii::$app->cache->delete("db-BuildingOrderMessages-getAllWithCache");
        Yii::$app->cache->delete("db-BuildingOrderMessages-getByIdWithCache/{$this->id}");
        static::getOrSetLastUpdatedAt(time());
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        $this->deleteCaches();
    }

    public function afterRefresh()
    {
        parent::afterRefresh();
        $this->deleteCaches();
    }

    public function afterDelete()
    {
        parent::afterDelete();
        $this->deleteCaches();
    }

    public function afterRestore()
    {
        $this->deleteCaches();
    }

    # relations

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCreatedByAdmin()
    {
        return $this->hasOne(Adminers::className(), ['id' => 'created_by_admin']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getUpdatedByAdmin()
    {
        return $this->hasOne(Adminers::className(), ['id' => 'updated_by_admin']);
    }

    # static funs

    public function test()
    {
        $test = self::instance();
        $test->setScenario(self::SCENARIO_TEST);
        $test->save();
        var_dump($test->toArray());
    }

    # funs

    public function getThumbedMessage()
    {
        $message = $this->message;
        $search = THIS_SERVER_BASE_URI.Yii::getAlias('@uploads_url');
        $replace = Yii::$app->urlManager->createAbsoluteUrl(['/pub/file/thumb'])."?src=".$search;
        $thumbed = str_replace($search, $replace, $message);
        return $thumbed;
    }

    public function getUnThumbedMessage()
    {

    }
}
